﻿using blog.Dao;
using blog.Model;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Data.SqlClient;

namespace blog.Controllers
{
    [Route("api/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        //SqlConnection conn = DBHelper.GetConn();

        //SqlDataReader rd = null;

        [HttpGet]
        public List<Users> SelectUserByName(string username)
        {
            List<Users> users = new List<Users>();           

            //1、定义SQL语句
            string sql = "select username from users where username=@username";

            //2、封装参数数组
            SqlParameter[] parameters =
            {
                new SqlParameter("@username",username)
            };

            //2、调用DataSet通用的查询的方法
            //DataSet ds=DBHelper.GetDataSet(sql,null);
            DataSet ds = DBHelper.GetDataSet(sql, parameters);

            //4、获得DataSet对象中指定的表（学生表）
            DataTable dt = ds.Tables[0];

            //5、遍历表中的每一行，把每行中的各个字段的值依次存入学生对象，添加学生对象到学生列表
            Users user = null;
            foreach (DataRow dr in dt.Rows)
            {
                user = new Users();
                user.Username = dr["username"].ToString();
                users.Add(user);
            }
            return users;
        }

        [HttpGet]
        public Result<Users> SelectUserById(int id)
        {
            Result<Users> res=new Result<Users>();

            //1、定义SQL语句
            string sql = "select * from users where id=@id";

            //2、封装参数数组
            SqlParameter[] parameters =
            {
                new SqlParameter("@id",id)
            };         
       
            DataSet ds = DBHelper.GetDataSet(sql, parameters);
            DataTable dt = ds.Tables[0];
            DataRow dr = dt.Rows[0];
            Users user = new Users();
            user.Id = Convert.ToInt32(dr["id"]);
            user.Username = dr["username"].ToString();
            user.Password = null;
            user.Nickname = dr["nickname"].ToString();
            user.Email = dr["email"].ToString();
            user.Address = dr["address"].ToString();
            user.Phone = dr["phone"].ToString();
            res.Code = 200;
            res.Message = "ok";
            res.Data = user;
            return res;
        }

        [HttpPost]
        public Result<int> UpdateUser([FromBody]Users user)
        {
            Result<int> res=new Result<int>();
            string md5_password = MD5Helper.Encrypt(user.Password);
            int count = 0;
            string sql = "update users set username=@username,password=@password,email=@email,address=@address,phone=@phone where id=@id";
            SqlParameter[] parameters =
            {
                new SqlParameter("@username",user.Username),
                new SqlParameter("@password",md5_password),
                new SqlParameter("@email",user.Email),
                new SqlParameter("@address",user.Address),
                new SqlParameter("@phone",user.Phone),
                new SqlParameter("@id",user.Id),
            };
            count = DBHelper.ExecuteNonQuery(sql, parameters);
            res.Message = "修改成功";
            res.Code = 200;
            res.Data = (int)user.Id;
            return res;
        }

        [HttpDelete]
        public Result<int> DeleteUser(int id)
        {
            Result<int> res = new Result<int>();
            int count = 0;
            string sql = "delete from users where id=@id";
            SqlParameter[] parameters =
            {
                new SqlParameter("@id",id)
            };

            count = DBHelper.ExecuteNonQuery(sql, parameters);
            res.Message = "删除成功";
            res.Code = 200;
            res.Data = count;
            return res;
        }

        [HttpPost]
        public Result<int> Register([FromBody]Users user)
        {
            Result<int> res = new Result<int>();
            string md5_password=MD5Helper.Encrypt(user.Password);
            int count = 0;
            string sql = "insert into users(username,password,nickname,email,address,phone,userAvatar) values(@username,@password,@nickname,@email,@address,@phone,@userAvatar)";
            SqlParameter[] parameters =
            {
                new SqlParameter("@username",user.Username),
                new SqlParameter("@password",md5_password),
                new SqlParameter("@nickname","user"),
                new SqlParameter("@email",user.Email),
                new SqlParameter("@address",user.Address),
                new SqlParameter("@phone",user.Phone),
                new SqlParameter("@userAvatar",user.UserAvatar),
            };
            
            if (SelectUserByName(user.Username).Count!=0)
            {
                res.Message = "用户名重复";
                res.Code = 100;
            }
            else
            {
                count= DBHelper.ExecuteNonQuery(sql, parameters);
                res.Message = "注册成功";
                res.Code = 200;                
            }
            res.Data = count;
            return res;
        }

        [HttpGet]
        public Result<int> CountUser()
        {
            Result<int> res = new Result<int>();
            string sql = "select count(*) from users";

            res.Data = (int)DBHelper.ExecuteScalar(sql);
            
            return res;
        }

        [HttpPost]
        public Result<Users> Login([FromBody]Users users)
        {
            Result <Users> res = new Result<Users>();

            //1、定义SQL语句
            string sql = "select * from users where username=@username";

            //2、封装参数数组
            SqlParameter[] parameters =
            {
                new SqlParameter("@username",users.Username)
            };

            //2、调用DataSet通用的查询的方法
            //DataSet ds=DBHelper.GetDataSet(sql,null);
            DataSet ds = DBHelper.GetDataSet(sql, parameters);

            //4、获得DataSet对象中指定的表（学生表）
            DataTable dt = ds.Tables[0];
            if (dt.Rows.Count == 0)
            {
                res.Code = 100;
                res.Message = "用户名或密码错误";
                res.Data = null;
                return res;
            }
            DataRow dr= dt.Rows[0];

            if (!MD5Helper.Encrypt(users.Password).Equals(dr["password"].ToString()))
            {
                res.Code = 100;
                res.Message = "用户名或密码错误";
                res.Data = null;
                return res;
            }

            //5、遍历表中的每一行，把每行中的各个字段的值依次存入学生对象，添加学生对象到学生列表
            Users user = new Users();
            user.Id = Convert.ToInt32(dr["id"]);
            user.Username = dr["username"].ToString();
            user.Password = null;
            user.Nickname = dr["nickname"].ToString();
            user.Email = dr["email"].ToString();
            user.Address = dr["address"].ToString();
            user.Phone = dr["phone"].ToString();
            res.Code = 200;
            res.Message= "登录成功";
            res.Data = user;
            return res;
        }

        [HttpGet]
        public Result<string> logout()
        {
            Result<string> res = new Result<string>();
            res.Code= 200;
            res.Message = "登出";
            return res;
        }

        [HttpGet]
        public Result<List<Users>> SelectAllUser()
        {
            Result<List<Users>> res = new Result<List<Users>>();
            List<Users> users = new List<Users>();
            string sql = "select * from users";

            //2、调用DataSet通用的查询的方法
            //DataSet ds=DBHelper.GetDataSet(sql,null);
            DataSet ds = DBHelper.GetDataSet(sql, null);

            //4、获得DataSet对象中指定的表（学生表）
            DataTable dt = ds.Tables[0];

            //5、遍历表中的每一行，把每行中的各个字段的值依次存入学生对象，添加学生对象到学生列表
            Users user = null;
            foreach (DataRow dr in dt.Rows)
            {
                user = new Users();
                user.Id = Convert.ToInt32(dr["id"]);
                user.Username = dr["username"].ToString();
                user.Password = dr["password"].ToString();
                user.Email = dr["email"].ToString();
                user.Phone = dr["phone"].ToString();
                user.Address = dr["address"].ToString();
                user.UserAvatar = dr["userAvatar"].ToString();
                users.Add(user);
            }
            res.Code = 200;
            res.Message = "查询成功";
            res.Data = users;
            return res;
        }

        [HttpGet]
        public Result<UserPage> UserPage()
        {
            Result<UserPage> res= new Result<UserPage>();
            List<Users>? list= new List<Users>();
            UserPage userPage= new UserPage();
            int total = 0;
            list = SelectAllUser().Data;
            total = CountUser().Data;
            userPage.Total = total;
            userPage.Users = list;
            res.Data=userPage;
            res.Code = 200;
            res.Data.Total = total;
            return res;
        }

    }
}
